package com.oasys.service.impl;

import com.oasys.dao.MenuMapper;
import com.oasys.entity.LoginUser;
import com.oasys.entity.MenuDto;
import com.oasys.entity.SysMenuEntity;
import com.oasys.enums.OaResponseCode;
import com.oasys.service.MenuService;
import com.oasys.service.SysUserService;
import com.oasys.utils.AutoGenerateIds;
import com.oasys.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/5/12
 **/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private SysUserService sysUserService;

    /**
     * 查询菜单
     * @param userId
     * @return
     */
    @Override
    public List<MenuDto> findMenusByUserId(Long userId) {
        try {
            //获取角色id
            Long roleId = menuMapper.getRoleByUserId(userId);
            MenuDto menuDto = null;
            //组装菜单list
            List<MenuDto> menuDtoList = new ArrayList<>();
            //当前角色所有菜单
            List<SysMenuEntity> menuList = null;
            List<Long> menuIds = null;
            if (null != roleId) {
                //获取角色菜单id
                menuIds = menuMapper.getMenuId(roleId);
            }
            if (ObjectUtils.isNotEmpty(menuIds)) {
                //角色所有菜单
                menuList = menuMapper.getMenuList(menuIds);
            }
            if (ObjectUtils.isNotEmpty(menuList)){
                for (SysMenuEntity sysMenu : menuList) {
                    //拼接二级菜单
                    if (null == sysMenu.getParentMenuId()){
                        menuDto = voToDto(sysMenu);
                        menuDtoList.add(menuDto);
                    }
                }
                //拼接三级菜单
                for (MenuDto dto : menuDtoList) {
                    Long menuId = dto.getMenuId();
                    dto.setChildList(menuList.stream().filter(x -> menuId.equals(x.getParentMenuId())).collect(Collectors.toList()));
                }
            }
            return menuDtoList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * SysMenuEntity转dto
     * @param menu
     * @return
     */
    public MenuDto voToDto(SysMenuEntity menu){
        MenuDto menuDto = new MenuDto();
        menuDto.setMenuId(menu.getMenuId());
        menuDto.setMenuName(menu.getMenuName());
        menuDto.setMenuIcon(menu.getMenuIcon());
        menuDto.setMenuCode(menu.getMenuCode());
        menuDto.setParentCode(menu.getParentCode());
        menuDto.setMenuType(menu.getMenuType());
        menuDto.setFlagInvalid(menu.getFlagInvalid());
        menuDto.setSkipPath(menu.getSkipPath());
        menuDto.setMenuSort(menu.getMenuSort());
        menu.setParentMenuId(menu.getParentMenuId());
        return menuDto;
    }

    /**
     * add
     * @param sysMenu sys
     * @return bool
     */
    @Override
    public Boolean addMenu(SysMenuEntity sysMenu) {
        Integer maxSort = 0;
        //跳转路径不能为空
        if (ObjectUtils.isEmpty(sysMenu) || null==sysMenu.getSkipPath() || "".equals(sysMenu.getSkipPath())){
            return false;
        }
        //如果父菜单id为空,则是二级菜单
        if (null == sysMenu.getParentMenuId()){
            //获取二级菜单当前最大的顺序号
            maxSort = menuMapper.findTwoLevelMenuMaxSort();
        }else {
            //如果子菜单不为空,是三级菜单,获取三级菜单最大顺序号(当前父级菜单下的最大顺序号)
            maxSort = menuMapper.findThreeLevelMenuMaxSort(sysMenu.getParentMenuId());
        }
        sysMenu.setMenuId(AutoGenerateIds.getGenerateId());
        sysMenu.setFlagInvalid(1);
        sysMenu.setMenuSort(null == maxSort ? 0 : maxSort + 1);
        return menuMapper.addMenu(sysMenu);
    }

    /**
     * 所有菜单
     * @return
     */
    @Override
    public List<MenuDto> getAllMenus() {
        List<SysMenuEntity> allMenus = menuMapper.getAllMenus();
        MenuDto menuDto = null;
        List<MenuDto> menuDtoList = new ArrayList<>();
        for (SysMenuEntity sysMenu : allMenus) {
            //拼接二级菜单
            if (null == sysMenu.getParentMenuId()){
                menuDto = voToDto(sysMenu);
                menuDtoList.add(menuDto);
            }
        }
        //拼接三级菜单
        for (MenuDto dto : menuDtoList) {
            Long menuId = dto.getMenuId();
            dto.setChildList(allMenus.stream().filter(x -> menuId.equals(x.getParentMenuId())).collect(Collectors.toList()));
        }
        return menuDtoList;
    }

    /**
     * 获取所有父级菜单
     * @return list
     */
    @Override
    public List<SysMenuEntity> getAllParentMenus(String menuName) {
        return menuMapper.getAllParentMenus(menuName);
    }

    /**
     * 当跳转路径 且 一级菜单id 为空时 表示添加一级菜单
     * 当跳转路径 且 一级菜单id 不为空时 表示添加二级菜单
     * 其他情况均返回false
     * 添加完菜单后默认给admin添加此菜单
     * @param sysMenu sys
     * @return bool
     */
    @Override
    public ResponseResult<Boolean> addMenuOne(SysMenuEntity sysMenu) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        Boolean bool,bool1 = false;
        LoginUser loginUser = sysUserService.getLoginUser();
        Long roleId = menuMapper.getRoleByUserId(loginUser.getUserId());
        sysMenu.setMenuId(AutoGenerateIds.getGenerateId());
        sysMenu.setMenuType(1);
        sysMenu.setFlagInvalid(1);
        //一级菜单
        if (StringUtils.isEmpty(sysMenu.getSkipPath()) && null == sysMenu.getParentMenuId()){
            Integer maxSort = menuMapper.findTwoLevelMenuMaxSort();
            sysMenu.setMenuSort(null == maxSort ? 0 : maxSort + 1);
            bool = menuMapper.addMenu(sysMenu);
            bool1 = menuMapper.addMenuForRole(AutoGenerateIds.getGenerateId(),roleId,sysMenu.getMenuId());
            result.setCode(OaResponseCode.SUCCESS.getCode());
            result.setData(bool && bool1);
            return result;
        }
        //二级菜单
        if (StringUtils.isNotEmpty(sysMenu.getSkipPath()) && null != sysMenu.getParentMenuId()){
            Integer maxSort = menuMapper.findThreeLevelMenuMaxSort(sysMenu.getParentMenuId());
            sysMenu.setMenuSort(null == maxSort ? 0 : maxSort + 1);
            bool = menuMapper.addMenu(sysMenu);
            bool1 = menuMapper.addMenuForRole(AutoGenerateIds.getGenerateId(),roleId,sysMenu.getMenuId());
            result.setCode(OaResponseCode.SUCCESS.getCode());
            result.setData(bool && bool1);
            return result;
        }
        result.setCode(OaResponseCode.FAIL.getCode());
        result.setMsg("上级菜单及跳转路径都为空 或 都不能为空!!!");
        result.setData(false);
        return result;
    }
}
